package com.probiz.estore.exports.handler.basic;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;

import com.probiz.estore.exports.handler.ColumnHandler;
import com.probiz.estore.exports.model.Column;
import com.probiz.estore.exports.util.ExportHelper;

public class BasicHandler implements ColumnHandler {
	
	public String getProperty(Object target, Column column, HSSFSheet sheet, HSSFRow row, List<String> listHeader){
		Object obj1 = target;
		Object obj = null;
		String properties[] = column.getAttrName().split("\\.");
		if(properties.length>0){
			for (String propertie : properties) {
				try {
					if(obj1 == null){
						continue;
					}
					obj = PropertyUtils.getProperty(obj1, propertie);
					if(properties.length > 1){
						obj1 = obj;
					}
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
				
			}
			obj1 = target;
		}
		if(obj != null){
			String str = obj.toString();
			if(column.getSelects()!=null){
				str = ExportHelper.toSelect(str, column);
			}
			if(column.isDate()){
				try {
					SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					str = sf.format(obj);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return str;
		} else {
			if(column.getDefaultValue() != null){
				return column.getDefaultValue();
			}
			return "";
		}
		
	}
}
